package cn.edu.swu.design.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.edu.swu.design.R
import cn.edu.swu.design.bean.ConstellationBean
import com.bumptech.glide.Glide
import com.oy.topline.R
import com.oy.topline.bean.ConstellationBean

class ChooseConstellaListAdapter(private val context: Context) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>(), View.OnClickListener {
    private var cbList: List<ConstellationBean>? = null
    private var mOnItemClickListener: OnItemClickListener? = null
    fun setOnItemClickListener(listener: (Any, Any) -> Unit) {
        mOnItemClickListener = listener
    }

    fun setData(cbList: List<ConstellationBean>?) {
        this.cbList = cbList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(viewGroup.context)
            .inflate(R.layout.choose_constella_item, viewGroup, false)
        val viewHolder: ViewHolder = ViewHolder(view)
        view.setOnClickListener(this)
        return viewHolder
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, i: Int) {
        val bean = cbList!![i]
        (holder as ViewHolder).tv_contella_name.text = bean.name
        holder.tv_date.text = bean.date
        Glide
            .with(context)
            .load(bean.img)
            .error(R.mipmap.ic_launcher)
            .into(holder.iv_img)
        //将i保存在itemView的Tag中，以便点击时进行获取
        holder.itemView.tag = i
    }

    override fun getItemCount(): Int {
        return if (cbList == null) 0 else cbList!!.size
    }

    override fun onClick(v: View) {
        if (mOnItemClickListener != null) {
            //注意这里使用getTag方法获取position
            mOnItemClickListener!!.onItemClick(v, v.tag as Int)
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tv_contella_name: TextView
        var tv_date: TextView
        var iv_img: ImageView

        init {
            tv_contella_name = itemView.findViewById<View>(R.id.tv_contella_name) as TextView
            tv_date = itemView.findViewById<View>(R.id.tv_date) as TextView
            iv_img = itemView.findViewById<View>(R.id.iv_constella_img) as ImageView
        }
    }

    interface OnItemClickListener {
        fun onItemClick(view: View?, position: Int)
    }
}